package org.example.springblogdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.example.springblogdemo.constants.Constants;
import org.example.springblogdemo.exception.BlogException;
import org.example.springblogdemo.mapper.BlogInfoMapper;
import org.example.springblogdemo.pojo.dataobject.BlogInfo;
import org.example.springblogdemo.pojo.request.AddBlogRequest;
import org.example.springblogdemo.pojo.request.UpdateBlogRequest;
import org.example.springblogdemo.respone.BlogInfoResponse;
import org.example.springblogdemo.service.BlogService;
import org.example.springblogdemo.util.BeanTransUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BlogServiceImpl implements BlogService {
    @Resource(name = "blogInfoMapper")
    private BlogInfoMapper blogInfoMapper;
    @Override
    public List<BlogInfoResponse> getList() {
        List<BlogInfo> blogInfos = blogInfoMapper.selectList(
                new LambdaQueryWrapper<BlogInfo>().eq(BlogInfo::getDeleteFlag, Constants.NOT_DELETE)
                        .orderByDesc(BlogInfo::getUpdateTime)
        );
        return blogInfos.stream().map(blogInfo -> BeanTransUtils.trans(blogInfo))
                .collect(Collectors.toList());
    }
    @Override
    public BlogInfoResponse getBlogDetail(Integer blogId) {
        return BeanTransUtils.trans(getBlogInfo(blogId));
    }
    @Override
    public BlogInfo getBlogInfo(Integer blogId){
        return blogInfoMapper.selectOne(
                new LambdaQueryWrapper<BlogInfo>().eq(BlogInfo::getDeleteFlag, Constants.NOT_DELETE)
                        .eq(BlogInfo::getId, blogId));
    }

    @Override
    public Boolean addBlog(AddBlogRequest addBlogRequest) {
        BlogInfo blogInfo = BeanTransUtils.transBlogInfo(addBlogRequest);
        try {
            blogInfoMapper.insert(blogInfo);
            return true;
        } catch (Exception e) {
            throw new BlogException("添加博客失败");
        }
    }

    @Override
    public Boolean updateBlog(UpdateBlogRequest updateBlogRequest) {
        BlogInfo blogInfo=BeanTransUtils.transBlogInfo(updateBlogRequest);
        try {
            int i = blogInfoMapper.updateById(blogInfo);
            return i==1;
        }catch (Exception e) {
            throw new BlogException("更新博客失败");
        }
    }

    @Override
    public Boolean deleteBlog(Integer blogId) {
        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setId(blogId);
        blogInfo.setDeleteFlag(Constants.IS_DELETE);
        try {
            int i = blogInfoMapper.updateById(blogInfo);
            return i==1;
        }catch (Exception e){
            throw new BlogException("删除博客失败");
        }
    }


}
